// dva文件
// 这4个是umi提供的ts的类型
import { Effect, Reducer, Subscription } from 'umi';
import { todolistApi } from '@/utils/api';

export interface IndexModelState {
  count: number;
  list: string[];
}

export interface IndexModelType {
  // 如果说一个字符串，不会取改变它的，可以直接拿它的值作为它的类型
  namespace: 'todolist';
  state: IndexModelState;
  effects: {
    // query: Effect;
    addAsync: Effect;
    getTodolistAsync: Effect;
  };
  reducers: {
    // save: Reducer;
    add: Reducer;
    minus: Reducer;
    addlist: Reducer;
    removelist: Reducer;
    getTodolist: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const dalay = (time: number) => {
  return new Promise((resolve) => {
    setTimeout((): void => {
      resolve(1);
    }, time);
  });
};

const IndexModel: IndexModelType = {
  // 命名空间(模块名称)
  namespace: 'todolist',

  // 仓库数据
  state: {
    count: 9,
    list: [],
  },

  // 写异步函数的（相当于vuex的actions）
  effects: {
    // *query({ payload }, { call, put }) {},
    *addAsync({ payload }, { call, put }) {
      yield dalay(1000);
      yield put({
        type: 'add',
      });
    },
    *getTodolistAsync({ payload }, { call, put }) {
      const res = yield call(todolistApi);
      yield put({
        type: 'getTodolist',
        list: res.list,
      });
    },
  },

  // 写同步函数的（相当于vuex的mutations）
  reducers: {
    // save(state, action) {
    //   return {
    //     ...state,
    //     ...action.payload,
    //   };
    // },
    add(state) {
      return {
        ...state,
        count: state.count + 1,
      };
    },
    minus(state, action) {
      return {
        ...state,
        count: state.count - action.num,
      };
    },
    addlist(state, action) {
      return {
        ...state,
        list: [...state.list, action.list],
      };
    },
    removelist(state, action) {
      return {
        ...state,
        list: state.list.filter((item: string) => item !== action.item),
      };
    },
    getTodolist(state, action) {
      return {
        ...state,
        list: action.list,
      };
    },
  },

  // 用于监听url的改变
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        // console.log(pathname);
        if (pathname === '/todolist') {
          dispatch({
            type: 'getTodolistAsync',
          });
        }
      });
    },
  },
};

export default IndexModel;
